package com.loren.demo03.tcp1;

import com.loren.demo03.tcp1.handler.TcpSocketClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class TcpSocketClient {

    private final String host;

    private final int port;

    private final Bootstrap bootstrap;

    private TcpSocketClient(String host, int port) {
        this.host = host;
        this.port = port;
        EventLoopGroup group = new NioEventLoopGroup();
        this.bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) {
                        socketChannel.pipeline().addLast(new TcpSocketClientHandler(TcpSocketClient.this));
                    }
                });
    }

    public void connectNettyServer() {
        ChannelFuture channelFuture = bootstrap.connect(this.host, this.port);
        channelFuture.addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                System.out.println("...TCP Client connect success...");
            } else {
                future.channel().pipeline().fireChannelInactive();
            }
        });
    }

    public static void main(String[] args) {
        TcpSocketClient tcpSocketClient = new TcpSocketClient("127.0.0.1", 9001);
        tcpSocketClient.connectNettyServer();
    }
}
